package com.scr1pt.extension

import com.scr1pt.extension.enum.EHashType
import com.scr1pt.extension.model.netcard.NetCard

/**
 * 说明: 集合扩展
 *
 * 创建者: tum0r
 *
 * 时间: 2021/8/25 14:46
 */

/**
 * 获取所有网卡信息
 */
fun ArrayList<NetCard>.getAllNetCards() = this.addAll(NetCard.getNetCards())

/**
 * 获取字节List的散列值
 *
 * @param[type] 散列值类型
 */
@JvmOverloads
fun List<Byte>.hash(type: EHashType = EHashType.SHA256): String = this.toByteArray().hash(type)

/**
 * 将集合转为强类型对象集合
 *
 * @param[targetClass] 目标强类型
 * @param[start] 字段的开始下标
 * @param[end] 字段的结束下标
 */
@JvmOverloads
fun <T> List<Array<Any?>>.arrayToObjects(targetClass: Class<T>, start: Int = 0, end: Int = if (this.isNotEmpty()) this[0].size else 0): ArrayList<T> {
    if (start < 0 || end > (if (this.isNotEmpty()) this[0].size else 0) || start >= end)
        throw ArrayIndexOutOfBoundsException("起始下标或结束下标不合法")
    val result = ArrayList<T>()
    if (targetClass.isPrimitiveType() || this.size <= 1 || this[0] as? Array<String> == null)
        return result
    val columnName = this[0].copyOfRange(start, end)
    for (i in 1 until this.size) {
        val list = this[i]
        val fields = targetClass.getAllFields()
        val item = targetClass.getConstructor().newInstance()
        var index: Int
        for (field in fields)
            if (columnName.lastIndexOf(field.name).also { index = it } >= 0)
                field.setObjectValue(item, list[index])
        result.add(item as T)
    }
    return result
}

/**
 * 将集合转为强类型对象集合
 *
 * @param[start] 字段的开始下标
 * @param[end] 字段的结束下标
 */
@JvmOverloads
inline fun <reified T> List<Array<Any?>>.arrayToObjects(start: Int = 0, end: Int = if (this.isNotEmpty()) this[0].size else 0): ArrayList<T> = this.arrayToObjects(T::class.java, start, end)


/**
 * 将集合转为强类型对象集合
 *
 * @param[targetClass] 目标强类型
 * @param[start] 字段的开始下标
 * @param[end] 字段的结束下标
 */
@JvmOverloads
fun <T> List<Map<String, Any?>>.mapToObjects(targetClass: Class<T>, start: Int = 0, end: Int = if (this.isNotEmpty()) this[0].size else 0): ArrayList<T> = this.toJSONArray().toObjects(targetClass, start, end)

/**
 * 将集合转为强类型对象集合
 *
 * @param[start] 字段的开始下标
 * @param[end] 字段的结束下标
 */
@JvmOverloads
inline fun <reified T> List<Map<String, Any?>>.mapToObjects(start: Int = 0, end: Int = if (this.isNotEmpty()) this[0].size else 0): ArrayList<T> = this.mapToObjects(T::class.java, start, end)